//
//  SCDBManager.swift
//  SecretChat
//
//  Created by TimTiger on 16/7/16.
//  Copyright © 2016年 TimTiger. All rights reserved.
//

import UIKit
import CoreData
import MudFramework

private let dbcontroller = SCDBController()

class SCDBController: NSObject {
    // MARK: - Core Data stack
    //share instance
    var persistentStoreCoordinator: NSPersistentStoreCoordinator?
    var managedObjectContext: NSManagedObjectContext!
    class var shareController: SCDBController {
       return dbcontroller
    }
    
    override init () {
        super.init()
        initPersistentStoreCoordinator()
        initManagedObjectContext()
    }
    
    func applicationDocumentsDirectory()->NSURL  {
        let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
        return urls[urls.count-1]
    }
    
    func managedObjectModel()->NSManagedObjectModel  {
        let modelURL = NSBundle.mainBundle().URLForResource("SecretChat", withExtension: "momd")!
        return NSManagedObjectModel(contentsOfURL: modelURL)!
    }
    
    func initPersistentStoreCoordinator() {
        var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel())
        let url = applicationDocumentsDirectory().URLByAppendingPathComponent("SecretChat.sqlite")
        let options = [NSMigratePersistentStoresAutomaticallyOption: NSNumber(bool: true),NSInferMappingModelAutomaticallyOption: NSNumber(bool: true)]
        do {
            try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: options)
        } catch let error1 as NSError {
            coordinator = nil
            var dict = [NSObject : AnyObject]()
            dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
            dict[NSLocalizedFailureReasonErrorKey] = "There was an error creating or loading the application's saved data."
            dict[NSUnderlyingErrorKey] = error1
            let error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict )
            MudLog("Unresolved error \(error), \(error.userInfo)")
        }
        self.persistentStoreCoordinator = coordinator
    }
    
    func initManagedObjectContext() {
        let coordinator = self.persistentStoreCoordinator
        if coordinator == nil {
            return
        }
        let managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType)
        managedObjectContext.persistentStoreCoordinator = coordinator
        self.managedObjectContext = managedObjectContext
    }
    
    // MARK: - Core Data Saving support
    func saveContext () {
        if let moc = self.managedObjectContext {
            var error: NSError? = nil
            if moc.hasChanges {
                do {
                    try moc.save()
                } catch let error1 as NSError {
                    error = error1
                    MudLog("Unresolved error \(error), \(error!.userInfo)")
                }
            }
        }
    }
}

